package com.biubiux2.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.timeout.IdleStateEvent;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author Lijinbao
 * @since 8/5/2022 6:20 PM
 */
public class MessageProtocolCodec extends MessageToMessageCodec<ByteBuf, ByteBuf> {

    private static final class MessageProtocolCodecHolder {
        static final MessageProtocolCodec messageProtocolCodec = new MessageProtocolCodec();
    }

    public static MessageProtocolCodec getInstance(){
        return MessageProtocolCodecHolder.messageProtocolCodec;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        int len = msg.readableBytes();
        ByteBuf nextBuf = PooledByteBufAllocator.DEFAULT.buffer(4 + len);

        nextBuf.writeInt(len);
        nextBuf.writeBytes(msg);

        out.add(nextBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        msg.readInt();
        msg.discardReadBytes();
        msg.retain();
        out.add(msg);
    }
}
